package com.zues.thread.design_mode.alternating_execute;

/**
 * 设计模式：演示交替执行Demo
 * 期望效果：三个线程，轮流打印a、b、c，打印5次
 * 线程1：a
 * 线程2：b
 * 线程3：c
 * 打印效果 ：abcabcabcabcabc
 *
 */
public class AlternatingExecuteDemo1 {


    public static void main(String[] args) {
        WaitNotify wm = new WaitNotify(1, 5);
        new Thread(()->{
            wm.print("a",1,2);
        },"t1").start();

        new Thread(()->{
            wm.print("b",2,3);
        },"t2").start();

        new Thread(()->{
            wm.print("c",3,1);
        },"t3").start();
    }

}

/**
 * 输出内容     等待标记        下一个标记
 * a               1               2
 * b               2               3
 * c               3               1
 */
class WaitNotify{

    //等待标记
    private int flag = 1;
    //循环次数
    private int loopNumber = 0;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    /**
     * 打印方法
     * @param str 打印字符串
     * @param waitFlag  当前等待标记
     * @param nextFlag  下一等待标记
     */
    public void print(String str,int waitFlag,int nextFlag){

        for (int i = 0; i < loopNumber; i++) {
            synchronized (this){
                while(flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }

}
